<!--工程员工管理 -->
<script setup lang="ts">
import {
  getPage,
  getForm,
  add,
  update,
  deletes,
  getSaleCustomerOptions,
} from "@/api/plan/planmodetail";
import {
  PlanMoDetailFormVO,
  PlanMoDetailQuery,
} from "@/api/plan/planmodetail/types";
import { ElMessage, ElMessageBox, ElForm } from "element-plus";

defineOptions({
  name: "PlanmodetailComponent", //
  inheritAttrs: false,
});

//参数
const props = defineProps({
  moNo: {
    type: String,
    default: () => {
      return "";
    },
  },
});

watch(
  () => props.moNo,
  (newVal: string) => {
    queryParams.moNo = newVal;
    formData.moNo = newVal;
    resetQuery();
  }
);

const queryFormRef = ref(ElForm);
const dataFormRef = ref(ElForm);

const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);

const queryParams = reactive<PlanMoDetailQuery>({
  pageNum: 1,
  pageSize: 10,
  moNo: props.moNo,
});

const updateTimeRange = ref("");
const pageist = ref<PlanMoDetailFormVO[]>();

watch(updateTimeRange, (newVal) => {
  if (newVal) {
    queryParams.startUpdateTime = newVal[0];
    queryParams.endUpdateTime = newVal[1];
  }
});

const dialog = reactive({
  title: "",
  visible: false,
});

//默认值
const formData = reactive<PlanMoDetailFormVO>({
  status: 1,
  remark: "",
  moNo: props.moNo,
});

const rules = reactive({
  itemNo: [{ required: true, message: "请输入 货号", trigger: "blur" }],
  moQty: [{ required: true, message: "请输入 mo数量", trigger: "blur" }],
});

/** 查询 */
function handleQuery() {
  loading.value = true;
  getPage(queryParams)
    .then(({ data }) => {
      pageist.value = data.list;
      console.log(pageist);
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

/**
 * 重置查询
 */
function resetQuery() {
  queryFormRef.value.resetFields();
  updateTimeRange.value = "";
  queryParams.pageNum = 1;
  queryParams.startUpdateTime = undefined;
  queryParams.endUpdateTime = undefined;
  queryParams.keywords = undefined;
  handleQuery();
}

/** 行复选框选中  */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.saleItemId);
}

/**
 * 打开表单弹窗
 *
 * @param id ID
 */
async function openEditDialog(id?: number) {
  dialog.visible = true;
  if (id) {
    dialog.title = "修改信息";
    getForm(id).then(({ data }) => {
      Object.assign(formData, data);
      console.log(formData);
    });
  } else {
    dialog.title = "新增";
  }

  //加载下拉数据
  await loadSaleCustomerOptions();
}

/**  表单提交 */
function handleSubmit() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      loading.value = false;
      const id = formData.planMoDetailId;
      if (id) {
        update(id, formData)
          .then(() => {
            ElMessage.success("修改成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        add(formData)
          .then(() => {
            ElMessage.success("新增成功");
            closeDialog();
            handleQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

/** 关闭弹窗 */
function closeDialog() {
  dialog.visible = false;
  resetForm();
}

/**  重置 表单 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  formData.coId = undefined;
  formData.status = 1;
}

/** 删除  */
function handleDelete(id?: number) {
  const idStrs = [id || ids.value].join(",");
  if (!idStrs) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    deletes(idStrs).then(() => {
      ElMessage.success("删除成功");
      resetQuery();
    });
  });
}

let saleCustomerList = [];

/** 加载工程员工下拉数据源 */
async function loadSaleCustomerOptions() {
  getSaleCustomerOptions().then((response) => {
    saleCustomerList = response.data;
    console.log(saleCustomerList);
  });
}

const dictDataDialog = reactive({
  title: "",
  visible: false,
});

/** 启动执行  */
onMounted(() => {
  handleQuery();
});
</script>

<template>
  <div class="app-container">
    <!--查询条件 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="关键字" prop="name">
          <el-input
            v-model="queryParams.keywords"
            placeholder="地址编号/客户编号"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item label="更新时间">
          <el-date-picker
            class="!w-[240px]"
            v-model="updateTimeRange"
            type="daterange"
            range-separator="~"
            start-placeholder="开始时间"
            end-placeholder="截止时间"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="handleQuery()"
            ><i-ep-search />搜索</el-button
          >
          <el-button @click="resetQuery()"><i-ep-refresh />重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <!--功能按钮 -->
      <template #header>
        <el-button
          v-hasPerm="['plan:planmodetail:add']"
          type="success"
          @click="openEditDialog()"
          ><i-ep-plus />新增</el-button
        >
        <el-button
          v-hasPerm="['plan:planmodetail:del']"
          type="danger"
          :disabled="ids.length === 0"
          @click="handleDelete()"
          ><i-ep-delete />删除</el-button
        >
      </template>

      <el-table
        v-loading="loading"
        highlight-current-row
        :data="pageist"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="MO单号" prop="moNo" width="120" />
        <el-table-column label="行号" prop="line" width="120" />

        <el-table-column label="货号" prop="itemNo" width="80" />

        <el-table-column label="子类" prop="ct" width="80" />
        <el-table-column label="批号" prop="lotNo" width="80" />
        <el-table-column label="MO数量" prop="moQty" width="80" />
        <el-table-column label="收货数量" prop="recQty" width="80" />
        <el-table-column label="开工日期" prop="startDate" width="80" />
        <el-table-column label="完工日期" prop="finishDate" width="80" />
        <el-table-column label="是否完成" prop="isFinish" width="80" />

        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag v-if="scope.row.status === 1" type="success">启用</el-tag>
            <el-tag v-else type="info">禁用</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="备注" prop="remark" align="center" />
        <el-table-column label="更新者" prop="updateName" align="center" />
        <el-table-column
          label="更新时间"
          prop="updateTime"
          align="center"
          width="160"
        />
        <el-table-column fixed="right" label="操作" align="center" width="160">
          <template #default="scope">
            <el-button
              v-hasPerm="['plan:planmodetail:edit']"
              type="primary"
              link
              size="small"
              @click.stop="openEditDialog(scope.row.planMoDetailId)"
              ><i-ep-edit />编辑</el-button
            >
            <el-button
              v-hasPerm="['plan:planmodetail:del']"
              type="primary"
              link
              size="small"
              @click.stop="handleDelete(scope.row.planMoDetailId)"
              ><i-ep-delete />删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="handleQuery"
      />
    </el-card>

    <!-- 弹出窗口 form -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="500px"
      @close="closeDialog"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="MO单号" prop="coNo">
          <el-input v-model="formData.moNo" placeholder="请输入 货号" />
        </el-form-item>

        <el-form-item label="行号" prop="rev">
          <el-input v-model="formData.line" placeholder="请输入 " />
        </el-form-item>
        <el-form-item label="货号" prop="itemNo">
          <el-input v-model="formData.itemNo" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="子类" prop="ct">
          <el-input v-model="formData.ct" placeholder="请输入 " />
        </el-form-item>

        <el-form-item label="批号" prop="lotNo">
          <el-input v-model="formData.lotNo" placeholder="请输入 " />
        </el-form-item>
        <el-form-item label="MO数量" prop="moQty">
          <el-input v-model="formData.moQty" placeholder="请输入 " />
        </el-form-item>
        <el-form-item label="收货数量" prop="recQty">
          <el-input v-model="formData.recQty" placeholder="请输入 " />
        </el-form-item>

        <el-form-item label="开工日期" prop="startDate">
          <el-date-picker
            class="!w-[240px]"
            v-model="formData.startDate"
            type="date"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item label="完工日期" prop="finishDate">
          <el-date-picker
            class="!w-[240px]"
            v-model="formData.finishDate"
            type="date"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item label="是否完成" prop="isFinish">
          <el-radio-group v-model="formData.isFinish">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            placeholder="请输入 备注"
            :autosize="{ minRows: 2, maxRows: 4 }"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
